"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: system_log.py
@DateTime: 2025/07/07
@Docs: 系统日志API
"""

from datetime import datetime
from typing import Annotated, Any

from fastapi import APIRouter, Depends, Query

from app.schemas.base import PaginatedResponse
from app.schemas.system import LoginLogRead, OperationLogRead
from app.services.system import login_log_service, operation_log_service
from app.utils.deps import PaginationDep, PermissionChecker

router = APIRouter()


# Dependency for Operation Log Filters
async def get_operation_log_filters(
    user_id: Annotated[int | None, Query(description="用户ID")] = None,
    module: Annotated[str | None, Query(description="操作模块")] = None,
    action: Annotated[str | None, Query(description="操作类型")] = None,
    start_time: Annotated[datetime | None, Query(description="开始时间")] = None,
    end_time: Annotated[datetime | None, Query(description="结束时间")] = None,
) -> dict[str, Any]:
    """操作日志查询参数依赖"""
    filters = {}
    if user_id is not None:
        filters["user_id"] = user_id
    if module:
        filters["module__icontains"] = module
    if action:
        filters["action__icontains"] = action
    if start_time:
        filters["created_at__gte"] = start_time
    if end_time:
        filters["created_at__lte"] = end_time
    return filters


# Dependency for Login Log Filters
async def get_login_log_filters(
    user_id: Annotated[int | None, Query(description="用户ID")] = None,
    is_success: Annotated[bool | None, Query(description="是否成功")] = None,
    start_time: Annotated[datetime | None, Query(description="开始时间")] = None,
    end_time: Annotated[datetime | None, Query(description="结束时间")] = None,
) -> dict[str, Any]:
    """登录日志查询参数依赖"""
    filters = {}
    if user_id is not None:
        filters["user_id"] = user_id
    if is_success is not None:
        filters["is_success"] = is_success
    if start_time:
        filters["login_at__gte"] = start_time
    if end_time:
        filters["login_at__lte"] = end_time
    return filters


OperationLogFilters = Annotated[dict[str, Any], Depends(get_operation_log_filters)]
LoginLogFilters = Annotated[dict[str, Any], Depends(get_login_log_filters)]


@router.get(
    "/operation-logs",
    response_model=PaginatedResponse[OperationLogRead],
    summary="获取操作日志列表",
    dependencies=[Depends(PermissionChecker("log:operation:read"))],
)
async def get_operation_logs(
    pagination: PaginationDep,
    filters: OperationLogFilters,
) -> PaginatedResponse[OperationLogRead]:
    """
    获取操作日志列表，支持分页和筛选。
    """
    logs, total = await operation_log_service.get_active_paginated(order_by=["-created_at"], **pagination, **filters)
    return PaginatedResponse(
        total=total,
        page=pagination["page"],
        page_size=pagination["page_size"],
        data=[OperationLogRead.model_validate(log) for log in logs],
    )


@router.get(
    "/login-logs",
    response_model=PaginatedResponse[LoginLogRead],
    summary="获取登录日志列表",
    dependencies=[Depends(PermissionChecker("log:login:read"))],
)
async def get_login_logs(
    pagination: PaginationDep,
    filters: LoginLogFilters,
) -> PaginatedResponse[LoginLogRead]:
    """
    获取登录日志列表，支持分页和筛选。
    """
    logs, total = await login_log_service.get_active_paginated(order_by=["-login_at"], **pagination, **filters)
    return PaginatedResponse(
        total=total,
        page=pagination["page"],
        page_size=pagination["page_size"],
        data=[LoginLogRead.model_validate(log) for log in logs],
    )
